import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:flutter_jl_bluetooth_plugin/flutter_jl_bluetooth_plugin.dart';
import 'package:flutter_jl_bluetooth_plugin/model/jl_peripheral_model.dart';
import 'package:flutter_jl_bluetooth/widgets/common_widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';

class PeripheralPage extends StatefulWidget {
  @override
  PeripheralPageState createState() => new PeripheralPageState();
}

class PeripheralPageState extends State<PeripheralPage> {
  String _pageTitle = "设备";
  bool _bleFilterEnable = false; // 设备是否过滤
  List<JLPeripheralModel> _deviceModelList = [];

  @override
  void initState() {
    // TODO: implement initState
    FlutterJlBluetoothPlugin.deviceListUpdateCallback =
        (List<JLPeripheralModel> deviceList, JLPeripheralState state) {
      switch (state) {
        case JLPeripheralState.connected:
          _pageTitle = "设备 - 已连接";
          break;
        case JLPeripheralState.disconnected:
          _pageTitle = "设备 - 未连接";
          break;
        case JLPeripheralState.update:
          break;
        default:
          print("deviceConnectCallback default: $state");
          break;
      }
      _deviceModelList = deviceList;
      if (mounted) setState(() {});
    };
    FlutterJlBluetoothPlugin.deviceConnectCallback = (JLPeripheralState state) {
      switch (state) {
        case JLPeripheralState.connected:
          Fluttertoast.showToast(
            msg: "连接成功",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
          );
          _pageTitle = "设备 - 已连接";
          break;
        case JLPeripheralState.disconnected:
          _pageTitle = "设备 - 未连接";
          break;
        case JLPeripheralState.refuse:
          Fluttertoast.showToast(
            msg: "蓝牙设备拒绝建立连接",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
          );
          _pageTitle = "设备 - 未连接";
          break;
        default:
          print("deviceConnectCallback default: $state");
          break;
      }
      if (mounted) setState(() {});
    };
    Future.delayed(Duration(seconds: 0), () async {
      await FlutterJlBluetoothPlugin().startScanBleDevice();
      _bleFilterEnable = await FlutterJlBluetoothPlugin().bleFilter;
      bool bleDeviceConnected =
          await FlutterJlBluetoothPlugin().bleDeviceConnected;
      if (bleDeviceConnected) {
        _pageTitle = "设备 - 已连接";
      } else {
        _pageTitle = "设备 - 未连接";
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  // 下拉刷新
  Future<void> onRefresh() async {
    await FlutterJlBluetoothPlugin().startScanBleDevice();
    await Future.delayed(Duration(seconds: 2));
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text(_pageTitle),
          backgroundColor: Colors.blueAccent, //设置appbar背景颜色
          centerTitle: true, //设置标题是否局中
        ),
        body: Column(
          children: [
            Platform.isIOS
                ? Container(
                    height: 50,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          margin: EdgeInsets.only(left: 8.0),
                          child: Text(
                            "是否过滤不吻合的BLE外设",
                            style: TextStyle(
                                fontSize: 16, color: Colors.blueAccent),
                          ),
                        ),
                        Container(
                          // margin: EdgeInsets.only(right: 8.0),
                          child: Switch(
                            value: _bleFilterEnable,
                            // activeColor: Colors.red,
                            onChanged: (bool value) async {
                              _bleFilterEnable = value;
                              await FlutterJlBluetoothPlugin()
                                  .setBleFilter(value);
                              await onRefresh();
                              setState(() {});
                            },
                          ),
                        ),
                      ],
                    ),
                  )
                : Container(),
            bottomWidget(),
            Expanded(
              child: RefreshIndicator(
                onRefresh: onRefresh,
                child: ListView.builder(
                  itemCount: _deviceModelList.length,
                  itemBuilder: (BuildContext context, int index) {
                    JLPeripheralModel deviceModel = _deviceModelList[index];
                    return _deviceWidget(deviceModel);
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 设备widget
  Widget _deviceWidget(JLPeripheralModel deviceModel) {
    return Container(
      height: 50,
      padding: const EdgeInsets.only(
        left: 8,
        right: 8,
      ),
      child: Column(
        children: [
          Container(
            height: 49,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  deviceModel.name ?? "未知设备名",
                  style: TextStyle(fontSize: 16),
                ),
                IconButton(
                    onPressed: () async {
                      // 判断手机是否开启蓝牙
                      bool phoneBluetoothEnable =
                          await FlutterJlBluetoothPlugin().phoneBluetoothEnable;
                      if (phoneBluetoothEnable == false) {
                        Fluttertoast.showToast(
                          msg: "手机蓝牙没有开启",
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.CENTER,
                        );
                        return;
                      }
                      if (deviceModel.state ==
                          JLPeripheralState.connected ||
                          deviceModel.state ==
                              JLPeripheralState.connecting) {
                        showCupertinoDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return CupertinoAlertDialog(
                                content: Text('是否断开连接？'),
                                actions: [
                                  CupertinoDialogAction(
                                    child: Text('取消'),
                                    onPressed: () async {
                                      Navigator.of(context).pop();
                                    },
                                  ),
                                  CupertinoDialogAction(
                                    child: Text('断开'),
                                    onPressed: () async {
                                      await FlutterJlBluetoothPlugin()
                                          .bleDisconnectToDevice();
                                      Navigator.of(context).pop();
                                    },
                                  ),
                                ],
                              );
                            });
                        return;
                      }
                      showCupertinoDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return CupertinoAlertDialog(
                              content: Text('是否通过认证方式连接BLE设备？'),
                              actions: [
                                CupertinoDialogAction(
                                  child: Text('认证连接'),
                                  onPressed: () async {
                                    await FlutterJlBluetoothPlugin()
                                        .bleConnectToDevice(
                                      identifier:
                                          deviceModel.identifier ??
                                              '',
                                      address:
                                          deviceModel.address ??
                                              '',
                                      blePairEnable: true,
                                    );
                                    Fluttertoast.showToast(
                                      msg:
                                          "蓝牙正在连接... ==> ${deviceModel.name ?? '未知设备名'}",
                                      toastLength: Toast.LENGTH_LONG,
                                      gravity: ToastGravity.CENTER,
                                    );
                                    Navigator.of(context).pop();
                                  },
                                ),
                                CupertinoDialogAction(
                                  child: Text('直接连接'),
                                  onPressed: () async {
                                    await FlutterJlBluetoothPlugin()
                                        .bleConnectToDevice(
                                      identifier:
                                          deviceModel.identifier ??
                                              '',
                                      address:
                                          deviceModel.address ??
                                              '',
                                      blePairEnable: false,
                                    );
                                    Fluttertoast.showToast(
                                      msg:
                                          "蓝牙正在连接... ==> ${deviceModel.name ?? '未知设备名'}",
                                      toastLength: Toast.LENGTH_LONG,
                                      gravity: ToastGravity.CENTER,
                                    );
                                    Navigator.of(context).pop();
                                  },
                                ),
                                CupertinoDialogAction(
                                  child: Text('取消'),
                                  onPressed: () async {
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            );
                          });
                    },
                    icon: Icon(
                      Icons.check_circle_outline,
                      color: deviceModel.state ==
                          JLPeripheralState.connected
                          ? Colors.blueAccent
                          : Colors.grey,
                    )),
              ],
            ),
          ),
          bottomWidget(),
        ],
      ),
    );
  }
}
